package com.demo.service;

import com.demo.mapper.UserMapper;
import com.demo.pojo.User;
import com.demo.utils.SaltUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author chenyuan
 * @date 2020/9/21 15:11
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    @Override
    public User getUserByName(String name) {
        return userMapper.getUserByName(name);
    }


    @Override
    public void addUser(User user) {
        int rows = userMapper.addUser(user);
        if (rows > 0){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }
    }

    @Override
    public void updateUser(String salt,int id ) {
        int rows = userMapper.updateUser(salt,id);
        if (rows > 0){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }
    }

    @Override
    public void deleteUser(int id) {
        int rows = userMapper.deleteUser(id);
        if (rows > 0){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }

    @Override
    public User getUserAndRole(String name) {
        return userMapper.getUserAndRole(name);
    }

    @Override
    public void register(User user) {
        // 生成随机盐
        String salt = SaltUtil.getSalt(8);
        // 将盐值存入数据库
        user.setSalt(salt);
        // 密码进行 MD5 + salt + hash 散列 加密
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt,1024);
        // 将 32 位密文存入
        user.setPassword(md5Hash.toHex());
        addUser(user);
    }
}
